Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

nice_things/io/read_line.sh

read_line

Since 0.3.0 · Source

import "{ read_line }" from nice_things/io/read_line.sh

Synopsis
read_line <out_line> [<out_trailing_lf>]

Configuration

Description
Read a line from stdin.

This function is meant to simplify the common pattern of reading a line without any processing and keeping the trailing line-feed character when present and without losing data when a file does not end in a new line, like so:

trailing_lf="
"
while IFS= read -r line || { trailing_lf= && [ -n "$line" ]; }; do
	: # Do something with "${line}${trailing_lf}"
done

As can be seen in the example above, reading a file correctly in sh, without losing any data, is awfully difficult. The same example using the read_line function is much more sensible:

while read_line line trailing_lf; do
	: # Do something with "${line}${trailing_lf}"
done

When the trailing line-feed is not necessary, the second parameter, <out_trailing_lf>, can be omitted.

Options

Operands

  • <out_line>: Output variable; the line will be written to this variable.
  • <out_trailing_lf>: Output variable; optional; the trailing line-feed character, if it exists, will be written to this variable.

Stdin
The line will be read from stdin.

Stdout

Stderr

Exit status

  • 0: Successful completion.
  • 1: End of file.

Abort

Usage examples

# Echo all text from stdin to stdout
while read_line line trailing_lf; do
	printf '%s' "${line}${trailing_lf}"
done